package com.atguigu.tingshu.user.login;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class LoginClient implements ApplicationContextAware {

    private static Map<Integer, ILogin> MAP = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beanMap = applicationContext.getBeansWithAnnotation(LoginBean.class);
        if (CollectionUtils.isEmpty(beanMap)){
            return;
        }
        // 遍历所有的具体策略类对象方法MAP中
        beanMap.values().forEach(bean -> {
            // 获取类上的注解对象
            LoginBean loginBean = bean.getClass().getAnnotation(LoginBean.class);
            MAP.put(loginBean.value().getType(), (ILogin) bean);
        });
    }

    public Map<String, String> login(LoginType loginType, LoginVo loginVo){
        return MAP.get(loginType.getType()).login(loginVo);
    }
}
